package com.gzc.just.play.last.war.common.connection;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.util.List;
import java.nio.ByteOrder;

/**
 * 消息解码器
 * 使用小端序解码，与Unity客户端协议兼容
 */
@Deprecated
public class MessageDecoder extends LengthFieldBasedFrameDecoder {
    
    public MessageDecoder() {
        // 使用小端序配置，最大帧长度1MB，长度字段偏移0，长度字段长度4字节
        super(ByteOrder.LITTLE_ENDIAN, 1024 * 1024, 0, 4, 0, 4, true);
    }
    
    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf frame = (ByteBuf) super.decode(ctx, in);
        if (frame == null) {
            return null;
        }
        
        try {
            // 读取消息ID
            if (frame.readableBytes() < 4) {
                throw new IllegalArgumentException("Frame too short to contain message ID");
            }
            int messageId = frame.readIntLE();
            
            // 读取消息体
            byte[] data = new byte[frame.readableBytes()];
            frame.readBytes(data);
            
            return new ServerMessage(messageId, data);
        } finally {
            frame.release();
        }
    }
    
    /**
     * 服务器消息
     */
    public static class ServerMessage {
        private final int messageId;
        private final byte[] data;
        
        public ServerMessage(int messageId, byte[] data) {
            this.messageId = messageId;
            this.data = data;
        }
        
        public int getMessageId() {
            return messageId;
        }
        
        public byte[] getData() {
            return data;
        }
    }
}